mui.init({
//	preloadPages:[{
//		id:'mobile_validRegister',
//		url:'validRegister.html'
//	}]
});
var old_back = mui.back;
mui.back = function(){
	var loginPageId = plus.storage.getItem(KeyCfg.loginPageId);
	if(loginPageId) plus.storage.removeItem(KeyCfg.loginPageId);
	var targetPage = plus.webview.getWebviewById(loginPageId);
	mui.fire(targetPage,'refresh',{});
	old_back();
}
/**
 * 刷新事件 
 * loginPageId
 */
window.addEventListener('refresh',function(event){
	FormMgr.resetFields(["userName","phone","password","password2","vcode","recommender"],true); /*清空字段*/
	document.getElementById("isRecommender").selectedIndex = 0;
	document.getElementById("information").selectedIndex = 0;
	var btn_register = $("#btn_register");
	btn_register.removeAttr("style");
	btn_register.text("注册");
//	btn_register.prop("disabled", true);
	setImgSrc();
});

function setImgSrc(){
	var vcodeUrl = UrlConfig.muser_validcode;
	var uuid = Math.random(1000);
	$("#img_vcode").attr("src",vcodeUrl+"?id="+uuid);
	$('#vcode').val("");
}
	
mui.plusReady(function() {
 	var url = UrlConfig.muser_getMessageSource;
	// 弹出系统等待对话框   
	MuiEventMgr.ajax(url,{pars:{},
	  	sfn : function(data){
	  		loadMessageSource(data);
	  	},ffn : function(err){
	  		mui.alert("获取数据失败：["+err+"]");
	  	}
	 });
 	function loadMessageSource(data){
 		var msg = data.msg;
 		var activeId = msg.activeId || "";
 		var list = msg.list;
 		$("#activeId").val(activeId);
 		var arr = ['<option value="">选择信息来源</option>'];
 		if(list && list.length > 0){
 			for(var i=0,count=list.length; i<count; i++){
 				var row = list[i];
 				var id = row.id;
 				var place = row.place;
 				arr[arr.length] = ['<option value="'+id+'">'+place+'</option>'];
 			}
 		}
 		$("#information").html(arr.join("  "));
 	}
 	
 	var errMsgArr = {};
 	/**--------- 验证码图片添加相关事件 CODE START ---------**/
 	function initEvents(){
 		setImgSrc();
 		
 		var ele_isRecommender = CmwMcore.$('isRecommender');
 		MeventMgr.onChange(ele_isRecommender, function(event,self){
 			var val = self.value;
 			if(val && val == '1'){
 				$("#recommender").show();
 				$("#sp_recomenderRow").show();
 			}else{
 				$("#recommender").hide();
 				$("#sp_recomenderRow").hide();
 			}
 			$("#recommender").val("");
 		});
 		
 		var ele_recommender = CmwMcore.$('recommender');
 		MeventMgr.onChange(ele_recommender, function(event,self){
 			var val = self.value;
 			var flag = validRecommender(val);
 			if(!flag) return false;
			validRecomenderByAjax(val);
 		});
 		
 		
 		var ele_img_vcode = CmwMcore.$('img_vcode');
		MeventMgr.onTouchstart(ele_img_vcode,function(event,self){
			setImgSrc();
			return false;
		});
		
		var ele_switch_vcode = CmwMcore.$('switch_vcode');
		MeventMgr.onTouchstart(ele_switch_vcode,function(event,self){
			setImgSrc();
			return false;
		});
		
		var btnRegister_protocol1 = CmwMcore.$('register_protocol1');
		MeventMgr.onTouchstart(btnRegister_protocol1,function(event,self){
			var cfg = {id:'mobile_register',pars :{}};
			MuiEventMgr.open("../protocol/protocolRegister.html",cfg);	
		});
		
		var btnRegister_protocol2 = CmwMcore.$('register_protocol2');
		MeventMgr.onTouchstart(btnRegister_protocol2,function(event,self){
			var cfg = {id:'mobile_register',pars :{}};
			MuiEventMgr.open("../mgrPro/mgrProtocol.html",cfg);	
		});
		
		
		/*------ 用户名校验  ------*/
		var ele_userName = CmwMcore.$('userName');
		MeventMgr.onChange(ele_userName,function(event,self){
			var url = UrlConfig.muser_checkusername;
			var ele = $("#userName");
			var userName = ele.val();
			var uerName_emptyText = ele.attr("placeholder");
			if(!userName || userName == uerName_emptyText){
				mui.alert("请输入用户名!");
				return;
			}
			if(errMsgArr["userName"]) delete errMsgArr["userName"];
			var data = {userName:userName};
			checkByRemote(url,data,"userName");
		});
		
		/*------ 手机校验  ------*/
		var ele_phone= CmwMcore.$('phone');
		MeventMgr.onChange(ele_phone,function(event,self){
			var url = UrlConfig.muser_checkmobile;
			var ele = $("#phone");
			var phone = ele.val();
			var phone_emptyText = ele.attr("placeholder");
			if(!phone || phone == phone_emptyText){
				mui.alert("请输入手机号码!");
				return;
			}
			if(errMsgArr["phone"]) delete errMsgArr["phone"];
			var data = {phone:phone};
			checkByRemote(url,data,"phone");
		});
		
		function checkByRemote(url,data,eleId){
			$.ajax(url, {  
		        data : data,  
		        dataType : 'jsonp',  
		        crossDomain: true,  
		        success: function(data) {
		        		data = JSON.parse(data);
		        		var success = data.success;
		        		var msg = data.msg;
		        		if(!success){
		        			if(!errMsgArr || errMsgArr.length == 0) errMsgArr = [];
		        			errMsgArr[eleId] = msg;
		        			$("#"+eleId).focus();
		        			mui.alert(msg);
		        		}else{
		        			if(!errMsgArr) return;
		        			if(errMsgArr[eleId]) delete errMsgArr[eleId];
		        		}
		        }
		    });
		}
 	}
 	initEvents();
 	/**--------- 验证码图片添加相关事件 CODE END ---------**/
 	
 	
 	var btnRegister = CmwMcore.$('btn_register');
	MeventMgr.onTouchstart(btnRegister,function(event,self){
		$("#btn_register").focus();
		if(!valid()) return;
		var ele_isRecommender = CmwMcore.$('isRecommender');
		var isRecommender = $("#isRecommender").val();
		if(isRecommender == 1){
			var recommender = $("#recommender").val();
			var flag = validRecommender(recommender);
 			if(!flag) return false;
			 validRecomenderByAjax(recommender,submitForm);
		}else{
			CmwMcore.disabled('btn_register');
			submitForm();
		}
		
	});
	
	/*表单验证*/
	function valid(){
//		for(var key in errMsgArr){
//			var errMsg = errMsgArr[key];
//			if(!errMsg) continue;
//			mui.alert(errMsg);
//			return;
//		}
		var eleUserName = $('#userName');
		var userName_val = eleUserName.val();
		var uerName_emptyText = eleUserName.attr("placeholder");
		
		if(!userName_val || userName_val.trim() == uerName_emptyText){
			eleUserName.focus();
			mui.alert("用户名：请输入5-20位字母/数字,例如：abc123!");
			return false;
		}
		var usern = /^[a-zA-Z0-9_]{1,}$/;
		if((userName_val.length<5 || userName_val.length>20) ||
		!userName_val.match(usern)){
			eleUserName.focus();
			mui.alert("用户名：请输入5-20位字母/数字,例如：abc123!");
			return false;
		}
		
		var elePhone = $('#phone');
		var phone_val = elePhone.val();
		var phone_emptyText = elePhone.attr("placeholder");
		//var phone_pattern = /^(?:13\d|14|15|18)-?\d{5}(\d{3}|\*{3})$/;
		//var phone_pattern = /^0?(13[0-9]|15[012356789]|18[0-9]|14[57]|170)[0-9]{8}$/;
		var phone_pattern = /^0?(1[0-9])[0-9]{9}$/;
		if(!phone_val || phone_val == phone_emptyText ||
			!phone_pattern.test(phone_val) || phone_val.length > 11){
			elePhone.focus();
			mui.alert("请输入正确的手机号码，例如：13500000000");
			return false;
		}
		
		var elePassword = $('#password');
		var password_val = elePassword.val();
		var password_emptyText = elePassword.attr("placeholder");
		var password_pattern = /^(?=[0-9a-zA-Z]+\d)(?=[0-9a-zA-Z]+[a-zA-Z])(?=[0-9a-zA-Z]).{8,16}$/;
		if(!password_val || password_val.trim() == password_emptyText ||
		 !password_pattern.test(password_val) || (password_val.length < 8  || password_val > 16)){
			elePassword.focus();
			mui.alert("密码：请输入8-16位字母加数字的组合,例如：Abc123456");
			return false;
		}
		
		var elePassword2 = $('#password2');
		var password2_val = elePassword2.val();
		var password2_emptyText = elePassword2.attr("placeholder");
		var password2_pattern = /^[A-Za-z0-9]+$/;
		if(!password2_val || password2_val.trim() == password2_emptyText){
			elePassword2.focus();
			mui.alert("请输入确认密码!");
			return false;
		}
		if(password_val != password2_val){
			elePassword2.focus();
			mui.alert("密码不一致!");
			return false;
		}
		
		var eleisRecommender = $("#isRecommender");
		var isRecommender_val = eleisRecommender.val();
		if(!isRecommender_val){
			eleisRecommender.focus();
			mui.alert("请选择推荐人!");
			return false;
		}
		var ele_recommender = $("#recommender");
		var recommender_val = ele_recommender.val();
		if(isRecommender_val == '1'){
			var flag = validRecommender(recommender_val);
			if(!flag) return flag;
		}
		
		var eleisinformation = $("#information");
		var information_val = eleisinformation.val();
		if(!information_val){
			eleisinformation.focus();
			mui.alert("请选择注册信息来源!");
			return false;
		}
		
		var eleVcode = $('#vcode');
		var vcode_val = eleVcode.val();
		var vcode_emptyText = eleVcode.attr("placeholder");
		if(!vcode_val || vcode_val == vcode_emptyText){
			eleVcode.focus();
			mui.alert("请输入验证码!");
			return false;
		}
		if(!$("input[name='agree']").is(":checked")){
			mui.alert("您还没有同意《来理财用户注册协议》!");
			return false;
		}
		
		
		
		return true;
	}
	
	/**
 		 * Ajax 远程验证推荐人 
 		 * @param {Object} phone
 		 * @param {Object} sfn_callback
 		 */
 		function validRecomenderByAjax(phone,sfn_callback){
 			var url = UrlConfig.muser_checkRecommenderMobile;
			MuiEventMgr.ajax(url,{pars:{phone:phone},
			  	sfn : function(data){
			  		var success = data.success;
			  		var msg = data.msg;
			  		var rNameVal = "";
			  		if(!success){
			  			mui.alert("推荐人手机号码不存在！");
			  			$("#sp_recomenderRow").hide();
			  		}else{
			  			$("#sp_recomenderRow").show();
			  			rNameVal = msg;
			  			if(sfn_callback) sfn_callback();
			  		}
			  		$("#sp_recomenderName").text(rNameVal);
			  	},ffn : function(err){
			  		mui.alert("获取数据失败：["+err+"]");
			  	}
			 });
 	}
 		
	/**
	 * 验证 推荐人手机号码格式是否正确
	 * @param {Object} recommender_val
	 */
	function validRecommender(recommender_val){
		var ele_recommender = $("#recommender");
		if(!recommender_val){
			ele_recommender.focus();
			mui.alert("请输入推荐人手机号码!");
			return false;
		}else{
			var phone_pattern = /^0?(1[0-9])[0-9]{9}$/;
			if(!phone_pattern.test(recommender_val) || recommender_val.length > 11){
				ele_recommender.focus();
				mui.alert("请输入正确的推荐人手机号码，例如：13500000000");
				return false;
			}
		}
		return true;
	}
	
	
	function submitForm(){
		var formDatas = $("#theForm").serialize();
		var url = UrlConfig.muser_save;
//		$.ajax(url, {
//	        data : formDatas,  
//	        dataType : 'jsonp',
//	        crossDomain: true,  
//	        success: function(data) {
//	        		console.log(data);
//	        		data = JSON.parse(data);
//	        		callback(data);
//	        		CmwMcore.enabled('btn_register');
//	        }
//	    });
	    
	   MuiEventMgr.ajax(url,{
	 	pars:formDatas,
	 	sfn : function(data){
        		callback(data);
        		CmwMcore.enabled('btn_register');
	 	},ffn : function(){
	 		CmwMcore.enabled('btn_register');
		 }
		});
	}
	
	function callback(data){
		var success = data.success;
		var msg = data.msg;
		if(!success){
			mui.alert(msg);
			return;
		}
		saveData(data.msg);
		forward(data.msg);
	}
	
	/**
	 * 保存数据到 storage 中
	 * @param {Object} data 要保存的用户数据
	 */
	function saveData(data){
		var sessionId = data[KeyCfg.JSESSIONID];
		var userId = data[KeyCfg.userId];
		var userName = $('#userName').val();
		plus.storage.setItem(KeyCfg.JSESSIONID, sessionId); 
		plus.storage.setItem(KeyCfg.userId, userId);
		plus.storage.setItem(KeyCfg.userName, userName);
		console.log("saveData.sessionId="+plus.storage.getItem(KeyCfg.JSESSIONID)+"\n");
		console.log("saveData.userId="+plus.storage.getItem(KeyCfg.userId)+"\n");
		console.log("saveData.userName="+plus.storage.getItem(KeyCfg.userName)+"\n");
	}
	
		
	
	
	function forward(data){
		var userId = data.userId;
		var phone = $("#phone").val();
		var pars = {userId:userId,phone:phone};
		var cfg = {id:'mobile_validRegister',pars : pars};
		plus.storage.removeItem(KeyCfg.targetPageId);
		MuiEventMgr.open("validRegister.html",cfg);
		//mui.fire(targetPage,"reload",pars);
	}
	
	var a_protocol = CmwMcore.$("a_protocol");
	MeventMgr.onTouchstart(a_protocol,function(event,self){
		var cfg = {pars :{}};
		MuiEventMgr.open('../protocol/protocolRegister.html',cfg);
		return false;
	});
});
